package cn.xfdzx.android.apps.shop.activity.ruzhu;


import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;

import java.io.File;
import java.io.IOException;
import java.net.Proxy;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpActivity;
import cn.xfdzx.android.apps.shop.bean.IdCardBeen;
import cn.xfdzx.android.apps.shop.bean.ShopIn1Been;
import cn.xfdzx.android.apps.shop.bean.ShopIn2Been;
import cn.xfdzx.android.apps.shop.bean.UploadImgBeen;
import cn.xfdzx.android.apps.shop.contract.IdCardContract;
import cn.xfdzx.android.apps.shop.presenter.IdCardPresenter;
import cn.xfdzx.android.apps.shop.util.GlideEngine;
import cn.xfdzx.android.apps.shop.util.ProgressDialog;
import cn.xfdzx.android.apps.shop.util.StatusBarUtil;
import cn.xfdzx.android.apps.shop.util.UtilsData;
import cn.xfdzx.android.apps.shop.util.UtilsLog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static cn.xfdzx.android.apps.shop.apps.Constants.APP_TOKEN;

public class XFDShopInZhengActivity extends BaseMvpActivity<IdCardPresenter> implements IdCardContract.View {

    @BindView(R.id.ll_state)
    LinearLayout llState;
    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.iv_id_card_1)
    ImageView ivIdCard1;
    @BindView(R.id.iv_id_card_2)
    ImageView ivIdCard2;
    @BindView(R.id.iv_saomiao)
    ImageView ivSaomiao;
    @BindView(R.id.ett_shop_name)
    EditText ettShopName;
  @BindView(R.id.ett_id_card)
    EditText ettIdCard;
    @BindView(R.id.ett_phone)
    EditText ettPhone;

    private RelativeLayout.LayoutParams item_bar;
    private Context mContext;
    protected Handler handler = new Handler();
    private boolean is_IdCard1 = false;
    private boolean is_IdCard2 = false;
    private boolean is_Saomiao = false;
    private String idcard_back_img = "", idcard_front_img = "", qs_img;
    private String type;


    private ShopIn2Been shopIn2Been;
    private Gson gson = new Gson();

    @Override
    public int getLayoutId() {
        return R.layout.activity_xfdshop_in_zheng;
    }

    @Override
    public void initView() {
        initHigh();
        mContext = XFDShopInZhengActivity.this;
        StatusBarUtil.setLightStatusBar(this, false, true);
        type = getIntent().getStringExtra("store_category");
        if (type.equals("0")) {
            llState.setBackgroundColor(getResources().getColor(R.color.color_FB9129));
            rlTitle.setBackgroundColor(getResources().getColor(R.color.color_FB9129));
            tvNext.setBackgroundResource(R.drawable.dfb9129_bg_r8);
        } else {

            llState.setBackgroundColor(getResources().getColor(R.color.color_02C557));
            rlTitle.setBackgroundColor(getResources().getColor(R.color.color_02C557));
            tvNext.setBackgroundResource(R.drawable.d02c557_bg_r8);
        }

        mPresenter = new IdCardPresenter();
        mPresenter.attachView(this);
//回显
        setText();
    }

    private void setText() {
        if (null == UtilsData.getPreference(this, "ruzhu").getString("shopIn2")) {
            shopIn2Been = new ShopIn2Been();
        } else {
            RoundedCorners roundedCorners = new RoundedCorners(10);
            //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
            RequestOptions options = RequestOptions.bitmapTransform(roundedCorners);
            shopIn2Been = gson.fromJson(UtilsData.getPreference(this, "ruzhu").getString("shopIn2"), ShopIn2Been.class);
            ettIdCard.setText(shopIn2Been.card_code+"");

            if (!shopIn2Been.idcard_front_img.isEmpty()) {
                is_IdCard1 = true;
                idcard_front_img = shopIn2Been.idcard_front_img;
                Glide.with(mContext).load(idcard_front_img).apply(options.transform(new CenterCrop(), roundedCorners)).into(ivIdCard1);
            }
            if (!shopIn2Been.idcard_back_img.isEmpty()) {
                is_IdCard2 = true;
                idcard_back_img = shopIn2Been.idcard_back_img;
                Glide.with(mContext).load(idcard_back_img).apply(options.transform(new CenterCrop(), roundedCorners)).into(ivIdCard2);
            }
            if (!shopIn2Been.qs_img.isEmpty()) {
                qs_img = shopIn2Been.qs_img;
                Glide.with(mContext).load(qs_img).apply(options.transform(new CenterCrop(), roundedCorners)).into(ivSaomiao);
            }

            ettShopName.setText(shopIn2Been.bd_name);
            ettPhone.setText(shopIn2Been.bd_phone);

        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        shopIn2Been.idcard_front_img = idcard_front_img;
        shopIn2Been.idcard_back_img = idcard_back_img;
        shopIn2Been.card_code = ettIdCard.getText().toString().trim();
        shopIn2Been.bd_name = ettShopName.getText().toString().trim();
        shopIn2Been.bd_phone = ettPhone.getText().toString().trim();
        shopIn2Been.store_phone = ettPhone.getText().toString().trim();
        shopIn2Been.qs_img = qs_img;
        UtilsData.getPreference(this, "ruzhu").put("shopIn2", gson.toJson(shopIn2Been));
    }

    private void initHigh() {
        item_bar = (RelativeLayout.LayoutParams) llState.getLayoutParams();
        item_bar.height = StatusBarUtil.getStatusBarHeight(this);
        llState.setLayoutParams(item_bar);
    }

    @Override
    public void showLoading() {
        ProgressDialog.getInstance().show(this);
    }

    @Override
    public void hideLoading() {
        ProgressDialog.getInstance().dismiss();
    }

    @Override
    public void onError(Throwable throwable) {

    }

    @Override
    public void onIdCardSuccess(IdCardBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            ettShopName.setText(bean.getData().getName());
            ettIdCard.setText( bean.getData().getIdNo());

        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @OnClick({R.id.tv_next, R.id.iv_back, R.id.iv_id_card_1, R.id.iv_id_card_2, R.id.iv_saomiao})
    public void Onclick(View view) {
        switch (view.getId()) {
            case R.id.tv_next:
                if (!is_IdCard1) {
                    Toast.makeText(mContext, "请上传手持身份证正面上半身照", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!is_IdCard2) {
                    Toast.makeText(mContext, "请上传手持身份证反面上半身照", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (ettShopName.getText().toString().trim().isEmpty()) {
                    Toast.makeText(mContext, "请填写真实姓名", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (ettPhone.getText().toString().trim().isEmpty()) {
                    Toast.makeText(mContext, "请填写手机号", Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent(this, XFDShopInBankNumActivity.class);
                intent.putExtra("store_phone", ettPhone.getText().toString().trim());
                intent.putExtra("idcard_back_img", idcard_back_img);
                intent.putExtra("idcard_front_img", idcard_front_img);
                intent.putExtra("qs_img", qs_img);
                intent.putExtra("bd_name", ettShopName.getText().toString().trim());
                intent.putExtra("bd_phone", ettPhone.getText().toString().trim());

                intent.putExtra("offline_shop_name", getIntent().getStringExtra("offline_shop_name"));
                intent.putExtra("store_name", getIntent().getStringExtra("store_name"));
                intent.putExtra("store_master", getIntent().getStringExtra("store_master"));
                intent.putExtra("store_qualifications_img", getIntent().getStringExtra("store_qualifications_img"));
                intent.putExtra("store_category", getIntent().getStringExtra("store_category"));
                intent.putExtra("store_address", getIntent().getStringExtra("store_address"));
                intent.putExtra("store_qualifications_num", getIntent().getStringExtra("store_qualifications_num"));
                intent.putExtra("store_qualifications_name", getIntent().getStringExtra("store_qualifications_name"));
                intent.putExtra("store_qualifications_expire", getIntent().getStringExtra("store_qualifications_expire"));
                intent.putExtra("store_logo", getIntent().getStringExtra("store_logo"));
                intent.putExtra("category_id", getIntent().getStringExtra("category_id"));
                intent.putExtra("whole_address", getIntent().getStringExtra("whole_address"));
                intent.putExtra("store_current_address", getIntent().getStringExtra("store_current_address"));
                intent.putExtra("intro", getIntent().getStringExtra("intro"));
                intent.putExtra("salecate", getIntent().getStringExtra("salecate"));
                intent.putExtra("front_door_photo", getIntent().getStringExtra("front_door_photo"));
                intent.putExtra("in_store_photo", getIntent().getStringExtra("in_store_photo"));
                intent.putExtra("bd_content", getIntent().getStringExtra("bd_content"));
                intent.putExtra("inv_code", getIntent().getStringExtra("inv_code"));
                intent.putExtra("lng", getIntent().getStringExtra("lng"));
                intent.putExtra("lat", getIntent().getStringExtra("lat"));
                intent.putExtra("store_num", getIntent().getStringExtra("store_num"));
                intent.putExtra("contract_year", getIntent().getStringExtra("contract_year"));
                intent.putExtra("card_code", ettIdCard.getText().toString().trim());


                startActivity(intent);
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_id_card_1:
                selectImage(ivIdCard1);
                break;
            case R.id.iv_id_card_2:
                selectImage(ivIdCard2);
                break;
            case R.id.iv_saomiao:
                selectImage(ivSaomiao);
                break;

        }
    }

    public void selectImage(ImageView imageView) {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage()).maxSelectNum(1)
                .loadImageEngine(GlideEngine.createGlideEngine())
                .minSelectNum(1).imageSpanCount(4)
                .selectionMode(PictureConfig.SINGLE)
                .compress(true)
                .minimumCompressSize(1000)
                .compressQuality(60)
                .isCamera(true)
                .previewImage(true)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        // onResult Callback
                        if (result.size() != 0) {
                            UtilsLog.error("dizhi", result.get(0).getCompressPath());
//                                    new File(result.get(0).getPath())
//                                    mPresenter.upload(new File(result.get(0).getPath()));
                            showLoading();
                            upLoadFiles(Constants.BASE_URL + "/addons/shimmer_liveshop/index.php/api/6/3/plugin/merch/common/apply/uploadImg", new File(result.get(0).getCompressPath()), new XFDShopInActivity.ConnectListener() {
                                @Override
                                public void connectSuccess(String result) {
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            hideLoading();
                                            try {
                                                Gson gson = new Gson();
                                                UploadImgBeen uploadImgBeen = gson.fromJson(result, UploadImgBeen.class);
                                                if (uploadImgBeen.getErrno().equals("200")) {

                                                    RoundedCorners roundedCorners = new RoundedCorners(10);
                                                    //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
                                                    RequestOptions options = RequestOptions.bitmapTransform(roundedCorners);
                                                    Glide.with(mContext).load(uploadImgBeen.getData().getSrc()).apply(options.transform(new CenterCrop(), roundedCorners)).into(imageView);
                                                    if (imageView == ivIdCard1) {
                                                        idcard_front_img = uploadImgBeen.getData().getSrc();
                                                        is_IdCard1 = true;
                                                        if (is_IdCard2) {
                                                            mPresenter.idCardSubmit(idcard_front_img, idcard_back_img);
                                                        }
                                                    } else if (imageView == ivIdCard2) {
                                                        is_IdCard2 = true;
                                                        idcard_back_img = uploadImgBeen.getData().getSrc();
                                                        if (is_IdCard1) {
                                                            mPresenter.idCardSubmit(idcard_front_img, idcard_back_img);
                                                        }
                                                    } else if (imageView == ivSaomiao) {
                                                        is_Saomiao = true;
                                                        qs_img = uploadImgBeen.getData().getSrc();
                                                    }

                                                } else {
                                                    Toast.makeText(mContext, uploadImgBeen.getMessage(), Toast.LENGTH_SHORT).show();
                                                }
                                            } catch (Exception e) {
                                                Toast.makeText(mContext, "上传失败", Toast.LENGTH_SHORT).show();

                                            }
                                        }
                                    });

                                }

                                @Override
                                public void connectFailed(String error) {
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            hideLoading();

                                        }
                                    });
                                }
                            });
                        }
                    }

                    @Override
                    public void onCancel() {
                        // onCancel Callback
                    }
                });
    }


    public void upLoadFiles(final String url, File file, final XFDShopInActivity.ConnectListener connectListener) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder().proxy(Proxy.NO_PROXY).connectTimeout(60 * 1000, TimeUnit.MILLISECONDS)
                .readTimeout(5 * 60 * 1000, TimeUnit.MILLISECONDS)
                .writeTimeout(5 * 60 * 1000, TimeUnit.MILLISECONDS)
                .build();
        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
        multipartBodyBuilder.setType(MultipartBody.FORM);
        //遍历map中所有参数到builder
        multipartBodyBuilder.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"), file));
        //构建请求体
        RequestBody requestBody = multipartBodyBuilder.build();
        Request.Builder RequestBuilder = new Request.Builder();
        RequestBuilder.url(url);// 添加URL地址
        RequestBuilder.post(requestBody);
        RequestBuilder.addHeader("Authori-zation", "Bearer " + APP_TOKEN);
        Request request = RequestBuilder.build();

        final Call call = okHttpClient.newCall(request);
        //异步get请求
        call.enqueue(new Callback() {
                         @Override
                         public void onFailure(Call call, IOException e) {
                             connectListener.connectFailed(e.toString());
                             UtilsLog.error("错误", e.toString());
                         }

                         @Override
                         public void onResponse(Call call, Response response) throws IOException {
                             String result = response.body().string();
                             connectListener.connectSuccess(result);
                             UtilsLog.error("成功", result);
                         }
                     }
        );
    }


    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }
}
